#include "stm32f4xx.h"
#include "jsonlib.h"
#include <stdlib.h>
#include <string.h> 
#define START_FLAG 1
#define END_FLAG 2
#define KEY_FLAG 4
#define VALUE_FLAG 8
#define QuotationMarks 16
#define ID "\"id\""
#define CMD "\"cmd\""
#define DATA "\"data\""
#define RESPONE "\"respone\""
#define CMD5 
#define CMD6 
#define CMD7 
#define CMD8 
#define CMD9 
#define CMD10 
#define CMD11 
#define CMD12 
typedef struct{
	uint32_t key_start;
	uint32_t key_len;
	uint32_t val_start;
	uint32_t val_len;
}strtype;

uint8_t isJson(char *str,CmdData *data,strtype type){

}
uint8_t getJson(CmdData *data,char *str,strtype type){
	char *tmp = str;
	char *key = (char *)malloc(sizeof(char)*type.key_len+1);
	char *value = (char *)malloc(sizeof(char)*type.val_len+1);
	tmp += (type.key_start);
	strncpy(key,tmp,type.key_len);
	key[type.key_len] = '\0';
	tmp = str;
	tmp += (type.val_start);
	strncpy(value,tmp,type.val_len);
	value[type.val_len] = '\0';
	if(strcmp(key,ID) == 0){
		data->id = atoi(value);
	}else if(strcmp(key,CMD) == 0){
		data->cmd = atoi(value);

	}else if(strcmp(key,DATA) == 0){
		data->data = (char *)malloc(sizeof(char)*type.val_len+1);
		snprintf(data->data,type.val_len,"%s",value);
	}else if(strcmp(key,RESPONE) == 0){
		data->respone = atoi(value);
	}
	return 1;
}
uint8_t split(char *str,CmdData *data){
	int i,len,str_len,str_index = 0;
	uint8_t flag = 0;

	strtype type={0,0,0,0};
	char *cpy_str = str;//(char *)malloc(sizeof(char)*strlen(str));
	char key[10],*value;
	flag |= START_FLAG;
	flag |= KEY_FLAG;
	str_len = strlen(str);
	for(i=0;i<str_len;i++)
	{
		if(cpy_str[i] == '{'){
			flag |= START_FLAG;
		}else if(cpy_str[i] == '}'){
			getJson(data,str,type);	

			flag |= END_FLAG;
		}else if(cpy_str[i] == ' '){
			
		}else if(cpy_str[i] == ','){
			flag |= KEY_FLAG;
			flag &= ~VALUE_FLAG;
			getJson(data,str,type);	
			memset((void *)&type,0,sizeof(type));
//		}else if(cpy_str[i] == '"'){
////				if(flag&QuotationMarks){

////				}else{
////					
////					if(flag&KEY_FLAG){
////							type.key_start = i+1;
////					}else{
////						type.val_start = i+1;
////					}
////				}
//			  flag ^= QuotationMarks;	
//				
		}else if(cpy_str[i] == ':'){
			flag &= ~KEY_FLAG;
			flag |= VALUE_FLAG;

		}else{
			if((flag&START_FLAG) == START_FLAG){
				if((flag&KEY_FLAG) == KEY_FLAG){					 	
						type.key_len++;
					  type.key_start = i - type.key_len+1;
				}else if((flag&VALUE_FLAG) == VALUE_FLAG){						
						type.val_len++;
					type.val_start = i - type.val_len+1;
				}

			}else
			{
			}

		}
	}
}
CmdData jsonbuf;
CmdData * JsonLoads(char *str){
		
		split(str,&jsonbuf);
		return (&jsonbuf);
}
char strbuf[200];
